//
//  SessionTools.m
//  FNer
//
//  Created by dllo on 15/11/7.
//  Copyright © 2015年 刘志强. All rights reserved.
//

#import "SessionTools.h"

@interface SessionTools ()<NSURLSessionDelegate>
@property(nonatomic,retain)NSURLSession *session;
@property(nonatomic,retain)NSURLSessionDataTask *task;
@property(nonatomic,retain)NSURLSessionDataTask *postTask;
@property(nonatomic,retain)NSURLSessionDownloadTask *downLoadTask;
@property(nonatomic,assign)NSInteger uID;
@end






@implementation SessionTools


+ (void)getLocalUrlWithNetUrl:(NSString *)str andID:(NSInteger)a andBlock:(sessionBlock)sessionB
{
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //NSURLSessionDownloadDelegate 签订协议

    SessionTools *s = [[SessionTools alloc]init];

    
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:s delegateQueue:[NSOperationQueue mainQueue]];
    //创建下载任务对象
    s.downLoadTask = [session downloadTaskWithRequest:request];
    [s.downLoadTask resume];//开始执行下载任务
    
    s.sessionB = sessionB;
    s.uID = a;

}

//下载完成掉用
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSLog(@"path===%@",location.path);//系统缓存路径
    NSLog(@"description===%@",location.description);//系统缓存路径
    NSLog(@"suggestedFilename===%@",downloadTask.response.suggestedFilename);//系统自动生成的文件名
    // response.suggestedFilename 系统建议使用的文件名，也可以自定义文件名
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    //保存视频
    //NSString *file = [caches stringByAppendingPathComponent:@"yutao.mp4"];
    
    //保存音乐

    NSString *file = [caches stringByAppendingPathComponent:[NSString stringWithFormat:@"lzq%ld.mp3" ,self.uID]];
    
    // 将临时文件移动到Caches文件夹
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    // AtPath : 源文件路径
    // ToPath : 目标文件路径
    [mgr moveItemAtPath:location.path toPath:file error:nil];
    
    NSLog(@"是否在主线程====%d",[NSThread isMainThread]);
    //因为在主线程,所以可以直接给imageview赋值
    //    self.myImageView.image = [UIImage imageWithContentsOfFile:file];
    NSLog(@"_______%@",file);
    self.sessionB(file);

}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    double progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
    NSLog(@"下载进度---%f", progress);
    
    NSLog(@"速度:%lldKB/s, 已经下载:%lldKB, 文件总大小%lldKB", bytesWritten / 1024, totalBytesWritten / 1024, totalBytesExpectedToWrite / 1024);
    
  // self.progress.progress = progress;
}







@end
